package com.lv.controller;

import com.lv.pojo.Admin;
import com.lv.pojo.LoginFrom;
import com.lv.pojo.Student;
import com.lv.pojo.Teacher;
import com.lv.service.AdminService;
import com.lv.service.StudentService;
import com.lv.service.TeacherService;
import com.lv.util.*;
import io.jsonwebtoken.Jwt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author:晓风残月Lx
 * @Date: 2022/4/28 19:10
 */

@Api(tags = "系统控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    AdminService adminService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    StudentService studentService;


    @ApiOperation("修改密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(
            @ApiParam("旧密码") @PathVariable("oldPwd") String oldPwd,
            @ApiParam("新密码") @PathVariable("newPwd") String newPwd,
            @ApiParam("获得登陆的令牌") @RequestHeader("token") String token
            ){
        boolean expiration = JwtHelper.isExpiration(token);
        if(expiration){
            //token过期
            return Result.fail().message("token过期了，请重新登录再修改密码");
        }
        //通过token获取当前登录的用户id 用户类型
        Long userId = JwtHelper.getUserId(token);
        //通过token获取当前登录的用户类型
        Integer userType = JwtHelper.getUserType(token);
        // 将明文密码转换为暗文
        oldPwd = MD5.encrypt(oldPwd);
        newPwd = MD5.encrypt(newPwd);

        switch (userType){
            case 1:
                Admin admin=adminService.updatePwd(userId,oldPwd);
                if(null!=admin){
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                }else{
                    return Result.fail().message("原密码输入错误");
                }
                break;

            case 2:
                Student student=studentService.updatePwd(userId,oldPwd);
                if(null!=student){
                    student.setPassword(newPwd);
                    studentService.saveOrUpdate(student);
                }else{
                    return Result.fail().message("原密码输入错误");
                }
                break;

            case 3:
                Teacher teacher=teacherService.updatePwd(userId,oldPwd);
                if(null!=teacher){
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                }else{
                    return Result.fail().message("原密码输入错误");
                }
                break;
        }

        return Result.ok();
    }


    @ApiOperation("文件上传统一入口")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
             @ApiParam("头像文件") @RequestPart("multipartFile")MultipartFile multipartFile
            ){
        String uuid= UUID.randomUUID().toString().replace("-","").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String newFileName = uuid.concat(originalFilename.substring(i));

        // 保存文件 将文件发送到第三方/独立的图片服务器上
        String portraitPath="D:\\software\\Java\\IDEA\\workspace\\zhxy\\target\\classes\\public\\upload/".concat(newFileName);
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //相应图片的路径
        String path = "upload/".concat(newFileName);
        return Result.ok(path);
    }


    @ApiOperation("通过token获取用户信息")
    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token")String token){
        // 获取用户中请求的token
        // 检查token 是否过期 20H
        boolean expiration = JwtHelper.isExpiration(token);
        if(expiration){
            return Result.build(null,ResultCodeEnum.TOKEN_ERROR);
        }
        // 解析token,获取用户id和用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        // 准备一个Map集合用于存响应的数据
        Map<String,Object> map=new HashMap<>();
        switch (userType){
            case 1:
                Admin admin=adminService.getAdminById(userId);
                map.put("user",admin);
                map.put("userType",1);
                break;
            case 2:
                Student student=studentService.getStudentById(userId);
                map.put("user",student);
                map.put("userType",2);
                break;
            case 3:
                Teacher teacher=teacherService.getTeacherById(userId);
                map.put("user",teacher);
                map.put("userType",3);
                break;
        }
        return Result.ok(map);
    }


    @ApiOperation("登录请求验证")
    @PostMapping("/login")
    public Result login(@RequestBody LoginFrom loginFrom,
                        HttpServletRequest request){
        // 验证码校验
        HttpSession session = request.getSession();
        String sessionVerifiCode = (String) session.getAttribute("verifiCode");
        String loginVerifiCode = loginFrom.getVerifiCode();
        if( "".equals(sessionVerifiCode) || null == sessionVerifiCode){
            return Result.fail().message("验证码失效，请刷新后重试");
        }
        if(!sessionVerifiCode.equalsIgnoreCase(loginVerifiCode)){
            return Result.fail().message("验证码有误，请重新输入");
        }
        //从session中移除现有验证码
        session.removeAttribute("verifiCode");

        // 分用户类型进行校验
        // 准备一个map 用户存放相应的数据
        Map<String,Object> map=new LinkedHashMap<>();
        switch (loginFrom.getUserType()){
            case 1:
                //管理员类型
                try {
                    Admin admin=adminService.login(loginFrom);
                    if(null != admin){
                        //用户的类型和用户id转换成一个密文，以token的名称向客户端反馈
                        String token = JwtHelper.createToken(admin.getId().longValue(), 1);
                        map.put("token",token);
                    }else{
                        throw new RuntimeException("用户名或者密码异常");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                //学生类型
                try {
                    Student student=studentService.login(loginFrom);
                    if(null != student){
                        map.put("token",JwtHelper.createToken(student.getId().longValue(),2));
                    }else{
                        throw new RuntimeException("用户名或者密码异常");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 3:
                //教师类型
                try {
                    Teacher teacher=teacherService.login(loginFrom);
                    if(null != teacher){
                        map.put("token",JwtHelper.createToken(teacher.getId().longValue(),3));
                    }else{
                        throw new RuntimeException("用户名或者密码异常");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }
        return Result.fail().message("查无此用户");


    }

    @ApiOperation("获取验证码图片")
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiController(HttpServletRequest request,
                                    HttpServletResponse response){
        // 获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        // 获取图片上的验证码
        String verifiCode =String.valueOf(CreateVerifiCodeImage.getVerifiCode());
        // 将验证码文本放入session域 为下一次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        // 将验证码图片响应给浏览器
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
